package com.sakuracard.stepdemo.util.json;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sakuracard.stepdemo.model.base.TransferableBaseEntity;
import com.sakuracard.stepdemo.util.json.adapter.TransferableBaseEntityAdapter;
import com.sakuracard.stepdemo.util.json.adapter.LocalDateTimeAdapter;
import com.sakuracard.stepdemo.util.json.adapter.SearchParamsAdapter;
import com.sakuracard.stepdemo.web.model.SearchParams;

import java.time.LocalDateTime;

public final class JsonUtils {
  private final static Gson JSON;

  static {
    JSON = new GsonBuilder()
        .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
        .registerTypeAdapter(SearchParams.class, new SearchParamsAdapter())
        .registerTypeHierarchyAdapter(TransferableBaseEntity.class, new TransferableBaseEntityAdapter())
        .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .serializeNulls()
        .create();
  }

  public static Gson getGson() {
    return JSON;
  }

  public static String serializeObject(Object data) {
    return JSON.toJson(data);
  }

  public static <T> T deserializeObject(String json, Class<T> clazz) {
    return JSON.fromJson(json, clazz);
  }
}
